package com.pirestupppai.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.pirestupppai.R;
import com.pirestupppai.adapter.SearchUserAdapter;
import com.pirestupppai.base.BaseAdapter;
import com.pirestupppai.base.BaseFragment;
import com.pirestupppai.base.BaseStatus;
import com.pirestupppai.bean.TupaiUser;
import com.pirestupppai.common.Constant;
import com.pirestupppai.network.NetworkRequest;
import com.pirestupppai.network.TupaiSubscriber;
import com.pirestupppai.rxbus.RxBus;
import com.pirestupppai.ui.activity.UserActivity;
import com.pirestupppai.widgets.view.CustomRecyclerView;
import com.pirestupppai.widgets.view.LoadMoreFooter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import rx.Subscription;
import rx.functions.Action1;

import static com.pirestupppai.rxbus.RxBus.RXBUS_SEARCH;

/**
 * 搜索用户
 *
 * @author: xiaoluo
 * @date: 2017-04-11 16:32
 */
public class SearchUserFragment extends BaseFragment {

    @BindView(R.id.search_user_recycler_view)
    CustomRecyclerView recyclerView;

    private LoadMoreFooter mFooterView;
    private SearchUserAdapter mSearchUserAdapter;
    private LinearLayoutManager mLinearLayoutManager;

    private int mPosition = 0;  // 列表最后一位
    private int mPage = 1;
    private int mSize = 20;
    private boolean hasMore = true;
    private List<TupaiUser> mSearchUserList = new ArrayList<>();
    private Subscription mSubscription;
    private String mSearchKey;

    @Override
    protected Context getFragmentContext() {
        return getActivity();
    }

    @Override
    protected int loadParentLayout() {
        return R.layout.fragment_search_user;
    }

    @Override
    protected void initViews() {
        mFooterView = new LoadMoreFooter(mContext);
        mSearchUserAdapter = new SearchUserAdapter(mContext, mSearchUserList);
        mSearchUserAdapter.addFooterView(mFooterView);
        mLinearLayoutManager = new LinearLayoutManager(mContext);
        mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        recyclerView.setEmptyText("暂无相关用户");
        recyclerView.getRecyclerView().setLayoutManager(mLinearLayoutManager);
        recyclerView.getRecyclerView().setAdapter(mSearchUserAdapter);
        recyclerView.getRecyclerView().setHasFixedSize(true);
    }

    @Override
    protected void initListeners() {
        // 监听到达底部事件
        recyclerView.getRecyclerView().addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //到达底部时,加载更多
                int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition() + 1;
                if (mLinearLayoutManager.getChildCount() > 0
                        && mLinearLayoutManager.getItemCount() >= mLinearLayoutManager.getChildCount()
                        && lastVisiblePosition >= mLinearLayoutManager.getItemCount()
                        && dy > 0) {
                    mPosition = lastVisiblePosition;

                    if (hasMore) {
                        mFooterView.setStatus(LoadMoreFooter.Status.LOADING);
                        searchUser(BaseStatus.LOADMORE);
                    }
                }
            }
        });

        mSearchUserAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                Intent intent = new Intent(mContext, UserActivity.class);
                intent.putExtra(Constant.IntentKey.UID, mSearchUserList.get(position).getId());
                mContext.startActivity(intent);
            }
        });
    }

    @Override
    protected void initLogic() {
        //注册观察者
        mSubscription = RxBus.getInstance()
                .toObservable(RXBUS_SEARCH, String.class)
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        mSearchKey = s;
                        searchUser(BaseStatus.REFRESH);
                    }
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (!mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
        }
    }

    /**
     * 搜索标签
     */
    private void searchUser(final BaseStatus status) {
        if (status == BaseStatus.REFRESH) {
            mFooterView.setStatus(LoadMoreFooter.Status.GONE);
            hasMore = true;
            mPage = 1;
        } else {
            mPage++;
        }
        NetworkRequest.getInstance().searchUser(mSearchKey, mPage, mSize, mContext,
                new TupaiSubscriber<List<TupaiUser>>(mContext) {
                    @Override
                    protected void requestSuccess(List<TupaiUser> users) {
                        if (users != null && users.size() != 0) {
                            recyclerView.noEmpty();
                            if (status == BaseStatus.REFRESH) {
                                mSearchUserList.clear();
                                mSearchUserList.addAll(users);
                                mSearchUserAdapter.notifyDataSetChanged();
                            } else {
                                mSearchUserList.addAll(users);
                                mSearchUserAdapter.notifyItemInserted(mPosition);
                            }
                        } else if (status == BaseStatus.REFRESH) {
                            recyclerView.setEmpty();
                        } else {
                            mFooterView.setStatus(LoadMoreFooter.Status.THE_END);
                        }

                        if (users != null && users.size() < mSize) {
                            mFooterView.setStatus(LoadMoreFooter.Status.THE_END);
                            hasMore = false;
                        }
                    }

                    @Override
                    protected void requestError(String error) {
                        if (status == BaseStatus.LOADMORE) {
                            mFooterView.setStatus(LoadMoreFooter.Status.GONE);
                            mPage--;
                        }
                    }
                });
    }
}


